/**
 * 
 */
package org.swing.utility.jai.bean;

/**
 * @author lqnhu
 *
 */
public class CellGrid {
	private Cell[][] cellArray;
	public int width;
	public int height;

	// Constructor
	public CellGrid(int gridWidth, int gridHeight) {
		width = gridWidth;
		height = gridHeight;
		cellArray = new Cell[gridWidth][gridHeight];
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				cellArray[x][y] = new Cell(x, y);
			}
		}
	}

	// Set all cells to dead status.
	public void clear() {
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				cellArray[x][y].alive = false;
			}
		}
	}

	// Set the specified cell to a particular status.
	public void setCellStatus(int col, int row, boolean alive) {
		cellArray[col][row].alive = alive;
	}

	// Get the specified cell's status
	public boolean getCellStatus(int col, int row) {
		return cellArray[col][row].alive;
	}

	// Jump to the next generation of the game.
	public void newGeneration() {
		Cell cell = null;
		// loop through each cell in the grid and
		// get its count of living neighbors.
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				cell = cellArray[x][y];
				cell.livingNeighbors = 0;
				for (int a = -1; a < 2; a++) {
					for (int b = -1; b < 2; b++) {
						Cell neighbor;
						try {
							neighbor = cellArray[cell.col + a][cell.row + b];
						} catch (Exception e) {
							continue;
						}
						if (!cell.equals(neighbor)) {
							if (neighbor.alive) {
								cell.livingNeighbors++;
							}
						}
					}
				}
			}
		}
		// loop through each cell again and apply the
		// rules to them based on amount of living neighbors.
		//
		// it seems somewhat excessive to have two loops
		// going through the cells, but it's necessary to get the
		// neighbor count for all cells _before_ applying the rules.
		// otherwise, the state is changing as you're going through
		// the grid, which makes for erratic (although neat looking!)
		// behavior.
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				cell = cellArray[x][y];
				if (cell.alive) {
					// this condenses conway's rules 1-3 into one statement
					if (cell.livingNeighbors != 2 && cell.livingNeighbors != 3) {
						cell.alive = false;
					}
				} else {
					// conway's rule 4
					if (cell.livingNeighbors == 3) {
						cell.alive = true;
					}
				}
			}
		}
	}
}
